package com.lagou.rabbitmq.publisherconfirm;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;

public class PublisherConfirmsProducer {

    public static void main(String[] args) throws Exception {

        ConnectionFactory factory = new ConnectionFactory();
        //指定协议 amqp://
        //指定用户名 root
        //指定密码 123456
        //指定host 47.115.74.219
        //指定端口号 5672
        //指定虚拟主机 %2f
        factory.setUri("amqp://root:123456@47.115.74.219:5672/%2f");

        Connection connection = factory.newConnection();

        Channel channel = connection.createChannel();

        //向RabbitMQ服务器发送AMQP命令，将当前通道标记为发送方确认通道
        AMQP.Confirm.SelectOk selectOk = channel.confirmSelect();

        channel.queueDeclare("queue.pc",true,false,false,null);
        channel.exchangeDeclare("ex.pc",BuiltinExchangeType.DIRECT,true,false,null);
        channel.queueBind("queue.pc","ex.pc","key.pc");

        channel.basicPublish("ex.pc","key.pc",null,"hello world".getBytes(StandardCharsets.UTF_8));

        //同步的方式等待RabbitMQ的确认消息

        try {
            channel.waitForConfirmsOrDie(5_000);
            System.out.println("发送的消息已经得到确认");
        }catch (IOException ex){
            System.out.println("消息被拒收");
        }catch (IllegalStateException ex){
            System.out.println("发送消息的通道不是PublisherConfirms通道");
        }catch (TimeoutException ex){
            System.out.println("等待消息确认超时");
        }

        channel.close();
        connection.close();

    }


}
